<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * Basketball extension for Joomleague
 * @version $Id: playersranking.php 79 2008-02-12 15:58:00Z julien.vonthron $
 * @package JlgBasketballExtension
 * @copyright Copyright (C) 2007 Julien Vonthron. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 * JlgBasketballExtension is free software and parts of it may contain or be derived from the
 * GNU General Public License or other free or open source software licenses.
 * 
 * contact: julien.vonthron[at]gmail.com 
 *   
 * Joomleague is a League Management and Prediction Game for Joomla!
 * Homepage: http://www.joomleague.de 
 *  
 */
?>

<?php
  
function showPlayersRanking( ) 
{
  global $joomleague, $database, $folder, $overall_config;
  global $mosConfig_absolute_path, $mosConfig_live_site, $Itemid;
  $divisionId = intval(mosGetParam( $_REQUEST , 'div', 0) );
  $divLevel = intval(mosGetParam( $_REQUEST , 'divLevel', 0) );
  $display_mode = intval(mosGetParam( $_REQUEST , 'display', 0) );
  
  $playerTable_config=array_merge($overall_config, $joomleague->getTemplateConfig("show_hockey_players_rank.tpl"));
  
  $limit = intval($playerTable_config['row_count'],10);
  
  if ( (!$divisionId) && $divLevel) { 
    $divs = $joomleague->getDivisionsId($divLevel); 
    
  }
  else {
    $divs = Array( $divisionId );
    if ($display_mode) $limit = 0;
  }
  
  $tables=Array();
  $tables_goalies=Array();
  foreach ($divs as $d) {
    $results = getPlayersRanking($joomleague, $d, $playerTable_config);
    if ( count($results) ) {
       $tables[$d] = ( $limit>0 ? array_slice( $results, 0, $limit ): $results );   
    }
    $results = getGoaliesRanking($joomleague, $d, $playerTable_config);
    if ( count($results) ) {
      //print_r($results);exit;
       $tables_goalies[$d] = ( $limit>0 ? array_slice( $results, 0, $limit ): $results );   
    }
  }
  $project = $joomleague;
  require (JL_TEMPLATE_PATH.'/tmpl/show_players_ranking.tpl.php');
}

/**
 * returns an array of players ordered by goals+assists
 *
 * @param object $project
 * @param int $divisionId
 * @param array $config
 * @param string $sort
 * @return array of players info object
 */
function getPlayersRanking( &$project, $divisionId = 0, &$config, $sort = 'points' ) {
  global $database;
  $evid1 = $config['event_goals'];
  $evid2 = $config['event_assists'];
  
  $query_SELECT = "SELECT SUM(me.event_sum) as ev, me.project_id,
                  p.id, p.firstname, p.lastname,
                  t.name as team_name, t.short_name as team_short_name, t.middle_name as team_middle_name,
                  pt.id as playertoolid, pt.team_id,
                  teamtool.id as teamtoolid";

  $query_FROM = " FROM #__joomleague_match_events AS me
                  INNER JOIN #__joomleague_matches AS m ON m.match_id = me.match_id
                  INNER JOIN #__joomleague_players AS p ON p.id = me.player_id
                  INNER JOIN #__joomleague_playertool AS pt ON me.player_id = pt.player_id AND pt.project_id = $project->id
                  INNER JOIN #__joomleague_teams AS t ON (pt.team_id = t.id AND (t.id = m.matchpart1 OR t.id = m.matchpart2))
                  INNER JOIN #__joomleague_team_joomleague AS teamtool ON teamtool.team_id = t.id AND teamtool.project_id = $project->id
                 ";
  
  $query_WHERE =" WHERE me.project_id = $project->id";
  $query_GROUP =" GROUP BY me.player_id, me.project_id ORDER BY NULL";

  if ( $divisionId ) {
    $query_FROM .=" INNER JOIN #__joomleague_divisions AS jldiv ON jldiv.id = teamtool.division_id";
    $query_WHERE .=" AND (jldiv.id = $divisionId OR jldiv.parent_id = $divisionId)";
  }
  
  $query_WHERE_EV =" AND me.event_type_id = $evid1";
  $database->setQuery($query_SELECT.$query_FROM.$query_WHERE.$query_WHERE_EV.$query_GROUP);
  if ( !$result1 = $database->loadObjectList() ) {
//    echo "<pre>";
//    echo $database->getErrorMsg();
//    echo "</pre>";
//    return;
  }

  $query_WHERE_EV =" AND me.event_type_id = $evid2";                            
  $database->setQuery($query_SELECT.$query_FROM.$query_WHERE.$query_WHERE_EV.$query_GROUP);
  if ( !$result2 = $database->loadObjectList() ) {
//    echo "<pre>";
//    echo $database->getErrorMsg();
//    echo "</pre>";
//    return;
  }
  
  $sum = Array();
  foreach ( $result1 as $r ) {
    if ( !(array_key_exists( $r->id, $sum ) ) ) {
      $sum[$r->id]=get_object_vars($r);
      $sum[$r->id]['ev1']=$r->ev;
      $sum[$r->id]['ev2']=0;
    }
    else $sum[$r->id]['ev1'] += $r->ev;
  }
  foreach ( $result2 as $r ) {
    if ( !(array_key_exists( $r->id, $sum ) ) ) {
      $sum[$r->id]=get_object_vars($r);
      $sum[$r->id]['ev1']=0;
      $sum[$r->id]['ev2']=$r->ev;
    }
    else $sum[$r->id]['ev2'] += $r->ev;
  }
  
  if (!function_exists ('cmpPlayersPoints')) {
    function cmpPlayersPoints ($a, $b) {
      return ($a['ev1']+$a['ev2']) < ($b['ev1']+$b['ev2']);
    }
  }
  
  usort($sum, 'cmpPlayersPoints');
  return ($sum);
}

/**
 * returns an array of goalies ordered by goals against average
 *
 * @param object $project
 * @param int $divisionId
 * @param array $config
 * @param string $sort
 * @return array of goalies info object
 */
function getGoaliesRanking( &$project, $divisionId = 0, &$config, $sort = 'points' ) {
  global $database;
  $evid1 = $config['event_goals_allowed'];
  $posGoalie = $config['goalie_position_id'];
  
  // sub request for games played
  $sub_games_played = "SELECT mp.player_id, COUNT(*) AS games_played
                        FROM #__joomleague_match_players AS mp
                        INNER JOIN #__joomleague_matches AS m USING (match_id)
                        WHERE m.project_id = $project->id
                          AND mp.position_id = $posGoalie
                        GROUP BY mp.player_id";
  
  // sub request for goals allowed
  $sub_goals_allowed = "SELECT player_id, SUM(event_sum) AS goals_allowed
                        FROM #__joomleague_match_events
                        WHERE project_id = $project->id
                          AND event_type_id = $evid1
                        GROUP BY player_id";
  
  // sub request for shutouts
  $sub_shutouts = "  SELECT mp.player_id, COUNT(*) as shutouts
                        FROM #__joomleague_match_players AS mp
                        INNER JOIN #__joomleague_matches AS m USING (match_id)
                        WHERE m.project_id = $project->id
                          AND mp.position_id = $posGoalie
                          AND NOT EXISTS (
                           SELECT * FROM #__joomleague_match_events AS me
                            WHERE me.player_id = mp.player_id
                              AND me.match_id = mp.match_id
                              AND event_type_id = $evid1
                            )
                        GROUP BY mp.player_id ";
  
  $query_SELECT = "SELECT goals_allowed, games_played, shutouts,
                    pt.project_id,
	                  p.id, p.firstname, p.lastname,
	                  t.name as team_name, t.short_name as team_short_name, t.middle_name as team_middle_name,
	                  pt.id as playertoolid, pt.position_id,
	                  teamtool.id as teamtoolid ";

  
  $query_FROM = " FROM #__joomleague_playertool AS pt
                  INNER JOIN #__joomleague_players AS p ON p.id = pt.player_id
                  INNER JOIN #__joomleague_teams AS t ON pt.team_id = t.id
                  INNER JOIN #__joomleague_team_joomleague AS teamtool ON teamtool.team_id = t.id AND teamtool.project_id = pt.project_id
                  INNER JOIN ($sub_games_played) AS gp ON p.id = gp.player_id
                  LEFT JOIN ($sub_goals_allowed) AS ga ON p.id = ga.player_id
                  LEFT JOIN ($sub_shutouts) AS sh ON p.id = sh.player_id
                  ";
  
  $query_WHERE =" WHERE pt.project_id = $project->id AND pt.position_id = $posGoalie";
  $query_GROUP =" GROUP BY pt.player_id ORDER BY NULL";

  if ( $divisionId ) {
    $query_FROM .=" INNER JOIN #__joomleague_divisions AS jldiv ON jldiv.id = teamtool.division_id";
    $query_WHERE .=" AND (jldiv.id = $divisionId OR jldiv.parent_id = $divisionId)";
  }
  
  $database->setQuery($query_SELECT.$query_FROM.$query_WHERE.$query_GROUP);
  if ( !$result1 = $database->loadObjectList() ) {
//    echo "<pre>";
//    echo $database->getErrorMsg();
//    echo "</pre>";
//    exit("debug");
  }
//  else {
//    echo "<pre>";
//    echo $database->getQuery();
//    print_r($result1);
//    echo "</pre>";
//    exit("debug2");
//  }
    
  if (!function_exists ('cmpGoalAverage')) {
    function cmpGoalAverage ($a, $b) {
    	//print_r($a);exit;
      if ($a->games_played == 0) return false;
      if ($b->games_played == 0) return true;
      return ($a->goals_allowed/$a->games_played) > ($b->goals_allowed/$b->games_played);
    }
  }
  
  usort($result1, 'cmpGoalAverage');
  //print_r($result1);exit;
  return ($result1);
}

?>
